/**
 * @author corey
 */
(function ($)
{

    $.conmenu = function (options)
    {
        items.push(options);
        $(options.selector).bind(window.opera ? 'click' : 'contextmenu', showmenu);
    };

    //defaults
    $.conmenu.containerType = 'div';
    $.conmenu.itemType = 'div';

    var items = [];
    var container = document.createElement($.conmenu.containerType);

    $(document).ready(function ()
    {
        $(container).hide().attr('id', 'conmenu').css('position', 'absolute').appendTo(document.body);
    });

    function showmenu(event)
    {
        event.stopPropagation();
        resetMenu();
        $(document.body).one('click', function ()
        {
            resetMenu();
        });
        if (window.opera && !event.ctrlKey) return;
        $.each(items, function ()
        {
            if ($.inArray(event.currentTarget, $(this.selector)) > -1)
            {
                $.each(this.choices, function ()
                {
                    action = this.action;
                    $(document.createElement($.conmenu.itemType)).html(this.label).click(function (clickEvent)
                    {
                        clickEvent.stopPropagation();
                        resetMenu();
                        action(event.currentTarget);
                    }).appendTo(container);
                });
            }
        });
        var size = {
            'height': $(window).height(),
            'width': $(window).width(),
            'sT': $(window).scrollTop(),
            'cW': $(container).width(),
            'cH': $(container).height()
        };

        $(container).addClass('contextmenu');

        $(container).css({
            'left': ((event.clientX + size.cW) > size.width ? (event.clientX - size.cW) : event.clientX),
            'top': ((event.clientY + size.cH) > size.height && event.clientY > size.cH ? (event.clientY + size.sT - size.cH) : event.clientY + size.sT)
        }).show();


        return false;
    }

    function resetMenu()
    {
        $(container).hide().empty();
    }

    // private function for debugging
    function debug(obj)
    {
        if (window.console && window.console.log)
        {
            window.console.log(obj);
        }
    };
})(jQuery);
